import React, { useState, useEffect } from 'react';
import {
  Typography,
  Card,
  Tabs,
  Row,
  Col,
  Divider,
  DatePicker,
  Button,
  Table,
  Tag,
  Progress,
  Spin,
  Empty,
  Alert,
  Space
} from 'antd';
import {
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  ClockCircleOutlined,
  UserOutlined,
  MessageOutlined,
  TeamOutlined,
  WarningOutlined,
  DownloadOutlined,
  ReloadOutlined,
  RobotOutlined
} from '@ant-design/icons';
import { ShieldOutlined, Statistic } from '../components/icons/IconComponents';
import { Area, Column, Pie, Line } from '@ant-design/plots';

const { Title, Paragraph } = Typography;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

const AnalyticsPage = () => {
  const [loading, setLoading] = useState(true);
  const [dateRange, setDateRange] = useState([null, null]);
  const [overviewData, setOverviewData] = useState(null);
  const [conversationData, setConversationData] = useState([]);
  const [puaDetectionData, setPuaDetectionData] = useState([]);
  const [usageData, setUsageData] = useState([]);
  const [topContactsData, setTopContactsData] = useState([]);
  const [puaTypesData, setPuaTypesData] = useState([]);

  // 获取统计数据
  useEffect(() => {
    const fetchAnalyticsData = async () => {
      setLoading(true);
      try {
        // 模拟数据 - 实际应用中应使用API
        setTimeout(() => {
          // 概览数据
          const mockOverviewData = {
            totalConversations: 1287,
            totalMessagesSent: 15482,
            totalMessagesReceived: 14329,
            activeDays: 68,
            totalContacts: 85,
            detectedPuaCount: 137,
            aiResponsesGenerated: 8753,
            averageResponseTime: 1.8,
          };
          setOverviewData(mockOverviewData);

          // 对话数据趋势
          const mockConversationData = [
            { date: '2023-09-01', messages: 212, conversations: 18 },
            { date: '2023-09-02', messages: 189, conversations: 15 },
            { date: '2023-09-03', messages: 267, conversations: 22 },
            { date: '2023-09-04', messages: 298, conversations: 25 },
            { date: '2023-09-05', messages: 310, conversations: 28 },
            { date: '2023-09-06', messages: 286, conversations: 24 },
            { date: '2023-09-07', messages: 315, conversations: 27 },
            { date: '2023-09-08', messages: 234, conversations: 21 },
            { date: '2023-09-09', messages: 248, conversations: 23 },
            { date: '2023-09-10', messages: 287, conversations: 26 },
            { date: '2023-09-11', messages: 302, conversations: 28 },
            { date: '2023-09-12', messages: 276, conversations: 25 },
            { date: '2023-09-13', messages: 328, conversations: 30 },
            { date: '2023-09-14', messages: 347, conversations: 32 },
          ];
          setConversationData(mockConversationData);

          // PUA检测数据
          const mockPuaDetectionData = [
            { date: '2023-09-01', count: 8, severity: 'low' },
            { date: '2023-09-02', count: 5, severity: 'medium' },
            { date: '2023-09-03', count: 3, severity: 'high' },
            { date: '2023-09-04', count: 7, severity: 'low' },
            { date: '2023-09-05', count: 12, severity: 'medium' },
            { date: '2023-09-06', count: 4, severity: 'high' },
            { date: '2023-09-07', count: 9, severity: 'low' },
            { date: '2023-09-08', count: 6, severity: 'medium' },
            { date: '2023-09-09', count: 2, severity: 'high' },
            { date: '2023-09-10', count: 11, severity: 'low' },
            { date: '2023-09-11', count: 8, severity: 'medium' },
            { date: '2023-09-12', count: 5, severity: 'high' },
            { date: '2023-09-13', count: 10, severity: 'low' },
            { date: '2023-09-14', count: 7, severity: 'medium' },
          ];
          setPuaDetectionData(mockPuaDetectionData);

          // 使用情况数据
          const mockUsageData = [
            { time: '00:00', count: 12 },
            { time: '01:00', count: 8 },
            { time: '02:00', count: 5 },
            { time: '03:00', count: 3 },
            { time: '04:00', count: 2 },
            { time: '05:00', count: 1 },
            { time: '06:00', count: 4 },
            { time: '07:00', count: 10 },
            { time: '08:00', count: 25 },
            { time: '09:00', count: 49 },
            { time: '10:00', count: 61 },
            { time: '11:00', count: 58 },
            { time: '12:00', count: 43 },
            { time: '13:00', count: 39 },
            { time: '14:00', count: 56 },
            { time: '15:00', count: 67 },
            { time: '16:00', count: 72 },
            { time: '17:00', count: 65 },
            { time: '18:00', count: 48 },
            { time: '19:00', count: 52 },
            { time: '20:00', count: 57 },
            { time: '21:00', count: 43 },
            { time: '22:00', count: 36 },
            { time: '23:00', count: 22 },
          ];
          setUsageData(mockUsageData);

          // 最常联系人数据
          const mockTopContactsData = [
            { name: '王小明', count: 487, percent: 12.8 },
            { name: '李梅', count: 356, percent: 9.4 },
            { name: '张伟', count: 312, percent: 8.2 },
            { name: '陈晓', count: 289, percent: 7.6 },
            { name: '刘芳', count: 275, percent: 7.2 },
          ];
          setTopContactsData(mockTopContactsData);

          // PUA类型数据
          const mockPuaTypesData = [
            { type: '情感操控', value: 42, percent: 30.7 },
            { type: '负面评价', value: 29, percent: 21.2 },
            { type: '爱情轰炸', value: 25, percent: 18.2 },
            { type: '孤立策略', value: 18, percent: 13.1 },
            { type: '其他类型', value: 23, percent: 16.8 },
          ];
          setPuaTypesData(mockPuaTypesData);
          
          setLoading(false);
        }, 1200);
        
        // 实际API调用示例：
        // const data = await analyticsService.getAnalyticsData(dateRange[0], dateRange[1]);
        // setOverviewData(data.overview);
        // setConversationData(data.conversationTrend);
        // setPuaDetectionData(data.puaDetection);
        // setUsageData(data.usageByTime);
        // setTopContactsData(data.topContacts);
        // setPuaTypesData(data.puaTypes);
        // setLoading(false);
      } catch (error) {
        console.error('获取分析数据失败:', error);
        setLoading(false);
      }
    };

    fetchAnalyticsData();
  }, [dateRange]);

  // 处理日期范围变化
  const handleDateRangeChange = (dates) => {
    setDateRange(dates);
  };

  // 导出数据
  const handleExportData = () => {
    // 实际应用中，这里应该调用导出数据的API
    console.log('导出数据', dateRange);
    // analyticsService.exportData(dateRange[0], dateRange[1]);
  };

  // 刷新数据
  const handleRefresh = () => {
    // 重新获取数据
    setDateRange([...dateRange]);
  };

  // 配置图表
  const conversationConfig = {
    data: conversationData,
    xField: 'date',
    yField: 'messages',
    seriesField: 'type',
    color: '#1890ff',
    columnStyle: {
      radius: [4, 4, 0, 0],
    },
    xAxis: {
      label: {
        autoRotate: true,
        autoHide: false,
        autoEllipsis: false,
      },
      title: {
        text: '日期',
      },
    },
    yAxis: {
      title: {
        text: '消息数量',
      },
    },
    meta: {
      date: {
        alias: '日期',
      },
      messages: {
        alias: '消息数量',
      },
    },
  };

  // PUA检测图表配置
  const puaDetectionConfig = {
    data: puaDetectionData,
    xField: 'date',
    yField: 'count',
    seriesField: 'severity',
    color: ({ severity }) => {
      if (severity === 'high') return '#ff4d4f';
      if (severity === 'medium') return '#faad14';
      return '#52c41a';
    },
    xAxis: {
      title: {
        text: '日期',
      },
    },
    yAxis: {
      title: {
        text: '检测次数',
      },
    },
  };

  // 使用时间图表配置
  const usageConfig = {
    data: usageData,
    xField: 'time',
    yField: 'count',
    xAxis: {
      title: {
        text: '时间',
      },
    },
    yAxis: {
      title: {
        text: '消息数量',
      },
    },
    smooth: true,
    color: '#722ed1',
  };

  // PUA类型饼图配置
  const puaTypesConfig = {
    data: puaTypesData,
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    innerRadius: 0.5,
    label: {
      type: 'inner',
      offset: '-50%',
      content: '{name} {percentage}',
      style: {
        fill: '#fff',
        fontSize: 14,
        textAlign: 'center',
      },
    },
    interactions: [{ type: 'element-active' }],
  };

  // 顶部联系人表格列定义
  const topContactsColumns = [
    {
      title: '联系人',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '消息数量',
      dataIndex: 'count',
      key: 'count',
      sorter: (a, b) => a.count - b.count,
    },
    {
      title: '占比',
      dataIndex: 'percent',
      key: 'percent',
      render: (percent) => `${percent}%`,
      sorter: (a, b) => a.percent - b.percent,
    },
    {
      title: '互动量',
      key: 'progress',
      render: (_, record) => (
        <Progress percent={record.percent} size="small" />
      ),
    },
  ];

  // PUA类型表格列定义
  const puaTypesColumns = [
    {
      title: 'PUA类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '检测次数',
      dataIndex: 'value',
      key: 'value',
      sorter: (a, b) => a.value - b.value,
    },
    {
      title: '占比',
      dataIndex: 'percent',
      key: 'percent',
      render: (percent) => `${percent}%`,
      sorter: (a, b) => a.percent - b.percent,
    },
    {
      title: '风险等级',
      key: 'risk',
      render: (_, record) => {
        let color = 'green';
        let text = '低';
        if (record.percent > 25) {
          color = 'red';
          text = '高';
        } else if (record.percent > 15) {
          color = 'orange';
          text = '中';
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
  ];

  return (
    <div>
      <Title level={2}>数据分析</Title>
      <Paragraph>
        查看详细的互动数据、PUA检测统计和使用情况分析。
      </Paragraph>
      
      <Card style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <RangePicker onChange={handleDateRangeChange} />
          <Space>
            <Button icon={<ReloadOutlined />} onClick={handleRefresh}>
              刷新
            </Button>
            <Button type="primary" icon={<DownloadOutlined />} onClick={handleExportData}>
              导出数据
            </Button>
          </Space>
        </div>
      </Card>
      
      <Spin spinning={loading}>
        {overviewData ? (
          <>
            <Card title="概览数据" style={{ marginBottom: 24 }}>
              <Row gutter={[24, 24]}>
                <Col xs={12} sm={12} md={8} lg={6}>
                  <Statistic 
                    title="总对话次数" 
                    value={overviewData.totalConversations} 
                    prefix={<MessageOutlined />} 
                  />
                </Col>
                <Col xs={12} sm={12} md={8} lg={6}>
                  <Statistic 
                    title="总发送消息" 
                    value={overviewData.totalMessagesSent} 
                    prefix={<UserOutlined />} 
                  />
                </Col>
                <Col xs={12} sm={12} md={8} lg={6}>
                  <Statistic 
                    title="总接收消息" 
                    value={overviewData.totalMessagesReceived} 
                    prefix={<TeamOutlined />} 
                  />
                </Col>
                <Col xs={12} sm={12} md={8} lg={6}>
                  <Statistic 
                    title="活跃天数" 
                    value={overviewData.activeDays} 
                    prefix={<ClockCircleOutlined />} 
                    suffix="天" 
                  />
                </Col>
                <Col xs={12} sm={12} md={8} lg={6}>
                  <Statistic 
                    title="联系人数量" 
                    value={overviewData.totalContacts} 
                    prefix={<TeamOutlined />} 
                  />
                </Col>
                <Col xs={12} sm={12} md={8} lg={6}>
                  <Statistic 
                    title="PUA检测次数" 
                    value={overviewData.detectedPuaCount} 
                    prefix={<WarningOutlined />} 
                    valueStyle={{ color: '#cf1322' }} 
                  />
                </Col>
                <Col xs={12} sm={12} md={8} lg={6}>
                  <Statistic 
                    title="AI回复生成次数" 
                    value={overviewData.aiResponsesGenerated} 
                    prefix={<RobotOutlined />} 
                  />
                </Col>
                <Col xs={12} sm={12} md={8} lg={6}>
                  <Statistic 
                    title="平均响应时间" 
                    value={overviewData.averageResponseTime} 
                    prefix={<ClockCircleOutlined />} 
                    suffix="秒" 
                    precision={1} 
                  />
                </Col>
              </Row>
            </Card>
            
            <Tabs defaultActiveKey="1">
              <TabPane 
                tab={
                  <span>
                    <BarChartOutlined />
                    对话趋势
                  </span>
                } 
                key="1"
              >
                <Card>
                  <Title level={4}>对话消息趋势</Title>
                  <Paragraph type="secondary">
                    展示每日的消息数量变化趋势，帮助了解使用频率。
                  </Paragraph>
                  <Column {...conversationConfig} />
                  
                  <Divider>最常联系人</Divider>
                  <Table 
                    dataSource={topContactsData} 
                    columns={topContactsColumns} 
                    rowKey="name"
                    pagination={false}
                  />
                </Card>
              </TabPane>
              
              <TabPane 
                tab={
                  <span>
                    <LineChartOutlined />
                    PUA检测分析
                  </span>
                } 
                key="2"
              >
                <Card>
                  <Alert
                    message="PUA检测提醒"
                    description="本系统会自动检测对话中可能的PUA行为，并分为低、中、高三个风险等级。高风险行为应引起重视。"
                    type="warning"
                    showIcon
                    style={{ marginBottom: 16 }}
                  />
                  
                  <Title level={4}>PUA检测趋势</Title>
                  <Paragraph type="secondary">
                    展示每日PUA检测次数及严重程度分布。
                  </Paragraph>
                  <Area {...puaDetectionConfig} />
                  
                  <Divider>PUA类型分布</Divider>
                  <Row gutter={24}>
                    <Col xs={24} md={12}>
                      <Pie {...puaTypesConfig} />
                    </Col>
                    <Col xs={24} md={12}>
                      <Table 
                        dataSource={puaTypesData} 
                        columns={puaTypesColumns} 
                        rowKey="type"
                        pagination={false}
                      />
                    </Col>
                  </Row>
                </Card>
              </TabPane>
              
              <TabPane 
                tab={
                  <span>
                    <PieChartOutlined />
                    使用情况分析
                  </span>
                } 
                key="3"
              >
                <Card>
                  <Title level={4}>使用时间分布</Title>
                  <Paragraph type="secondary">
                    展示一天中不同时段的使用频率，帮助了解使用习惯。
                  </Paragraph>
                  <Line {...usageConfig} />
                  
                  <Divider>使用时间统计</Divider>
                  <Row gutter={[24, 24]}>
                    <Col xs={24} sm={12} md={8} lg={6}>
                      <Card>
                        <Statistic 
                          title="早晨 (6:00-12:00)" 
                          value={190} 
                          suffix="条消息" 
                        />
                      </Card>
                    </Col>
                    <Col xs={24} sm={12} md={8} lg={6}>
                      <Card>
                        <Statistic 
                          title="下午 (12:00-18:00)" 
                          value={342} 
                          suffix="条消息" 
                        />
                      </Card>
                    </Col>
                    <Col xs={24} sm={12} md={8} lg={6}>
                      <Card>
                        <Statistic 
                          title="晚上 (18:00-24:00)" 
                          value={258} 
                          suffix="条消息" 
                        />
                      </Card>
                    </Col>
                    <Col xs={24} sm={12} md={8} lg={6}>
                      <Card>
                        <Statistic 
                          title="深夜 (0:00-6:00)" 
                          value={31} 
                          suffix="条消息" 
                        />
                      </Card>
                    </Col>
                  </Row>
                </Card>
              </TabPane>
            </Tabs>
          </>
        ) : !loading ? (
          <Empty 
            description="暂无分析数据" 
            image={Empty.PRESENTED_IMAGE_SIMPLE} 
          />
        ) : null}
      </Spin>
    </div>
  );
};

export default AnalyticsPage; 